<template>
  <view class="container">
    <!-- 筛选区域 -->
    <view class="filter-card">
      <view class="filter-header">
        <text class="filter-title">数据筛选</text>
        <view class="filter-actions">
          <button class="reset-btn" @click="handleReset">重置</button>
          <button class="query-btn" @click="handleQuery">查询</button>
        </view>
      </view>
      
      <view class="filter-body">
        <!-- 数据类型选择 -->
        <view class="filter-group">
          <text class="group-label">数据类型</text>
          <picker class="type-selector" mode="selector" :range="dataTypes" range-key="name" @change="onTypeChange">
            <view class="selector-content">
              <text class="selector-value">{{dataTypes[typeIndex].name}}</text>
              <image class="arrow-icon" src="/static/arrow-down.png"></image>
            </view>
          </picker>
        </view>
        
        <!-- 开始时间 -->
        <view class="filter-group">
          <text class="group-label">开始时间</text>
          <picker mode="date" fields="day" @change="onStartDateChange">
            <view class="time-picker">
              <text class="time-value">{{start || '请选择开始时间'}}</text>
              <image class="calendar-icon" src="/static/calendar.png"></image>
            </view>
          </picker>
        </view>
        
        <!-- 结束时间 -->
        <view class="filter-group">
          <text class="group-label">结束时间</text>
          <picker mode="date" fields="day" @change="onEndDateChange">
            <view class="time-picker">
              <text class="time-value">{{end || '请选择结束时间'}}</text>
              <image class="calendar-icon" src="/static/calendar.png"></image>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 图表 -->
    <ucharts
	   v-if="chartData"
	  :title="chartTitle"
	  :subtitle="'单位：' + unit"
	  type=1
	  :categories="timeData"
	  :seriesData="chartData"
	  ref="uchart"
    />

    <!-- 数据列表 -->
    <view class="data-section">
      <view class="data-header">
        <text class="data-title">历史记录</text>
        <text class="data-count">共{{tableData.length}}条</text>
      </view>
      <view class="data-list"> 
        <view class="data-item" v-for="(item, index) in tableData" :key="index">
          <text class="data-time">{{item.time}}</text>
          <text class="data-value" style="margin-left: 50px;">{{item.value}}{{unit}}</text>
          <image class="data-trend" src="/static/up.png" v-if="item.trend > 0"></image>
		  <image class="data-trend" src="/static/down.png" v-if="item.trend < 0"></image>
		  <image class="data-trend" src="/static/line.png" v-if="item.trend === 0"></image>
        </view>
      </view>
      
      <!-- 分页 -->
      <view class="pagination">
        <button 
          class="page-btn" 
          :disabled="pageIndex <= 1" 
          @click="handlePageChange(pageIndex - 1)"
        >
          上一页
        </button>
        <text class="page-info">{{pageIndex}}/{{pages}}</text>
        <button 
          class="page-btn" 
          :disabled="pageIndex >= pages" 
          @click="handlePageChange(pageIndex + 1)"
        >
          下一页
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import ucharts from '../../components/ucharts/ucharts.vue';

export default {
  components: {
	ucharts
  },
  data() {
    return {
      tableData: [],  // 表格数据
      pages: 1,       // 总页数
      pageIndex: 1,   // 当前页码
      typeIndex: 0,    // 默认选中环境温度
      dataTypes: [
        { name: '环境温度', type: 'hjwd', unit: '℃' },
        { name: '湿度', type: 'sd', unit: '%' },
        { name: '血氧', type: 'xy', unit: '%' },
        { name: '心率', type: 'xl', unit: '次/分' },
        { name: '人体体温', type: 'rtwd', unit: '℃' },
        { name: '胎压', type: 'ty', unit: 'kPa' },
        { name: '骑行速度', type: 'qxsd', unit: 'km/h' }
      ],
      start: '',      // 开始时间，默认为空
      end: '',        // 结束时间，默认为空
	  mqttWs:null
    }
  },
  computed: {
    currentType() {
      return this.dataTypes[this.typeIndex].type;
    },
    unit() {
      return this.dataTypes[this.typeIndex].unit;
    },
	chartTitle(){
		return this.dataTypes[this.typeIndex].name + '走势图'
	},
	timeData(){
		return this.tableData.map(item => {
			let a = item.time.split(' ')[1]
			let b = a.split(':')
			return b[0] + ':' + b[1]
		}) || []
	},
	chartData(){
		return this.tableData.map(item => item.value) || []
	}
  },
  async onShow() {
	await this.loadData();
  	if(!this.mqttWs){
  		this.mqtt()
  	}
  },
  onHide(){
  	if(this.mqttWs){
  		this.mqttWs.close({
			success(){
						console.log('关闭成功')
			},
			fail(){
				console.log('关闭失败')
			}
		})
  		this.mqttWs = null
  	}
  },
  methods: {
    mqtt(){
		let url = this.$wsUrl + '/mqtt'
		this.mqttWs = uni.connectSocket({
			url:url,
			success(){
				console.log(url + ' 连接成功')
			},
			fail(){
				console.log(url + ' 连接失败')
			}
		})
		this.mqttWs.onMessage(async(res)=>{ 
			if(JSON.parse(res.data).topic === 'sensor_data'){
				const result = await this.sendWs();
				this.tableData = result.tableData || [];
				this.pages = result.pages || 1;
				await this.$nextTick();
				if (this.$refs.uchart) {
				  this.$refs.uchart.isDataReady = true;
				}
			}
		})
	},
    async loadData() {
      try {
        const result = await this.sendWs();
        this.tableData = result.tableData || [];
        this.pages = result.pages || 1;
		this.flag = true
		await this.$nextTick();
		if (this.$refs.uchart) {
		  this.$refs.uchart.isDataReady = true;
		}
      } catch (error) {
        console.error('加载数据失败:', error);
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      }
    },
    
    sendWs() {
      return new Promise((resolve, reject) => {
        let url = this.$wsUrl + '/history';
        const ws = uni.connectSocket({
			url:url,
			success(){
				console.log(url + ' 连接成功')
			},
			fail(){
				console.log(url + ' 连接失败')
			}
		})
        ws.onOpen(() => {
          ws.send({
			data:JSON.stringify({
				type: this.currentType,
				start: this.start,
				end: this.end,
				pageIndex: this.pageIndex
			})
		  })
        });
        ws.onMessage((e) => {
          resolve(JSON.parse(e.data));
          ws.close({
				success(){
						console.log(url + '关闭成功')
					},
					fail(){
						console.log(url + '关闭失败')
					}
			})
        });
      });
    },
    
    onTypeChange(e) {
      this.typeIndex = e.detail.value;
      this.handleQuery();
    },
    
    onStartDateChange(e) {
      this.start = e.detail.value;
    },
    
    onEndDateChange(e) {
      this.end = e.detail.value;
    },
    
    handleQuery() {
      this.pageIndex = 1;
      this.loadData();
    },
    
    handleReset() {
      this.typeIndex = 0;
      this.start = '';
      this.end = '';
      this.pageIndex = 1;
      this.handleQuery();
    },
    
    handlePageChange(newPage) {
      if (newPage >= 1 && newPage <= this.pages) {
        this.pageIndex = newPage;
        this.loadData();
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 筛选卡片样式 */
.filter-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.filter-actions {
  display: flex;
  gap: 8px;
}

.reset-btn {
  background: #f5f7fa;
  color: #666;
  border-radius: 6px;
  font-size: 14px;
  padding: 0 12px;
  height: 32px;
  line-height: 32px;
}

.query-btn {
  background: #4a8fd8;
  color: white;
  border-radius: 6px;
  font-size: 14px;
  padding: 0 16px;
  height: 32px;
  line-height: 32px;
}

/* 筛选内容区域 */
.filter-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.group-label {
  font-size: 14px;
  color: #666;
}

/* 数据类型选择器 */
.type-selector {
  width: 100%;
}

.selector-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #eaeaea;
}

.selector-value {
  font-size: 14px;
  color: #333;
}

.arrow-icon {
  width: 16px;
  height: 16px;
}

/* 时间选择器 */
.time-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #eaeaea;
}

.time-value {
  font-size: 14px;
  color: #333;
}

.calendar-icon {
  width: 16px;
  height: 16px;
}

/* 图表容器 */
.qiun-charts {
  width: 100%;
  height: 300px;
}

/* 数据列表区域 */
.data-section {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.data-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.data-count {
  font-size: 14px;
  color: #999;
}

.data-list {
  max-height: 600rpx;
  overflow-y: auto;
}

.data-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.data-item:last-child {
  border-bottom: none;
}

.data-time {
  font-size: 14px;
  color: #666;
  width: 180rpx;
}

.data-value { 
  font-size: 14px;
  color: #333;
  flex: 1;
}

.data-trend {
  width: 18px;
  height: 18px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 16px;
  gap: 16px;
}

.page-btn {
  font-size: 12px;
  padding: 6px 12px;
  background: #f5f7fa;
  border-radius: 4px; 
} 

.page-btn[disabled] {
  opacity: 0.5;
}

.page-info {
  font-size: 14px;
  color: #666;
}
</style>